package com.myshiro.controller;

import com.myshiro.pojo.SysRight;
import com.myshiro.pojo.SysRole;
import com.myshiro.pojo.SysUser;
import com.myshiro.service.SysRightService;
import com.myshiro.utils.Constants;
import com.myshiro.utils.PasswordUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class LoginController {

    @Resource
    SysRightService rightService;

   @RequestMapping({"/","login"})
    public String login(){
       return "login";
   }

    @RequestMapping({"logout"})
    public String logout(){
        return "login";
    }

    @RequestMapping({"doLogin","doLogin.html"})
    public String doLogin(@RequestParam("usrName") String username
                        , @RequestParam("usrPassword") String password
                        , Model model
                        , HttpServletRequest request){

       //调用service.login方法,验证用户名是否正确

        try {

            //password = PasswordUtil.encryptPassword(password,"czkt");

            UsernamePasswordToken token = new UsernamePasswordToken(username,password);

            Subject subject = SecurityUtils.getSubject();
            subject.login(token); // --> 账密给了shiro

            //调用后台方法实现登录逻辑的验证
            //认证|登录-->shiro
            SysUser currUser = (SysUser) subject.getPrincipal(); // 从shiro再次拿回 principal

            //动态授权
            //根据当前登录用户的roleid,查询他有的所有的权限

            //按roleId查
            SysRole role = currUser.getRole();
            List<SysRight> rights = rightService.getSysRightByUserRoleId(role.getRoleId());
            role.getRights().addAll(rights); //把用户的权限列表,放入role->user

            //放入session
            request.getSession().setAttribute(Constants.currUser,currUser);

            return "redirect:main";  //没有抛异常,就是代表认证成功
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg","账密错误,登录失败");
        }catch (LockedAccountException  e) {
            model.addAttribute("msg",e.getMessage());//被锁定
        }catch (AuthenticationException e) {
            model.addAttribute("msg","认证异常,登录失败");
        }

        return "login";
    }
    @RequestMapping({"main"})
    public String main(){
        return "main";
    }

    @RequestMapping({"/unauthorizedUrl"})
    public String unauthorizedUrl(){
        return "403";
    }

}
